package com.qf.config;

import com.qf.dao.PermissionRepository;
import com.qf.dao.SellerMapper;
import com.qf.dao.UserMapper;
import com.qf.dao.UserRepository;
import com.qf.pojo.entity.Seller;
import com.qf.pojo.entity.Users;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    SellerMapper sellerMapper;

    @Autowired
    PermissionRepository permissionRepository;

   //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        List<String> list = permissionRepository.selectPerNameByUserName(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(list);
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        Seller byName = sellerMapper.findByName(userName);

        if (byName!=null){
            return new SimpleAuthenticationInfo(userName,byName.getPassword(),ByteSource.Util.bytes(userName),this.getName());
        }
        return null;
    }
}
